package com.javastudy.liuhouse.lambda.stream;

import org.junit.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

//Reduce聚合
public class ReduceStream {

    @Test
    public void testReduce01(){
        Integer sum = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
                .reduce(0, (acc, n) -> acc + n);
        System.out.println(sum);
    }


    @Test
    public void testReduce02(){
        Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
        Optional<Integer> opt = integerStream.reduce((acc, n) -> acc + n);
        if(opt.isPresent()){
            System.out.println(opt.get());
        }
    }

    @Test
    public void testReduce03(){
        //有初始化值的时候就可以判断出返回值
        Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
        Integer reduce = integerStream.reduce(1, (acc, n) -> acc * n);
        System.out.println(reduce);
    }


    @Test
    public void testReduce04(){
        //按行读取配置文件
        //按行读取配置文件
        List<String> props = List.of("profile=native", "debug=true", "logging=warn", "interval=500");
        Map<String, String> map = props.stream()
                //将k=v转换为 Map[k] = v
                .map(kv -> {
                    String[] ss = kv.split("=", 2);
                    return Map.of(ss[0], ss[1]);//java21有的特性
                })
                //把所有的Map聚合到一个Map:
                .reduce(new HashMap<String, String>(), (m, kv) -> {
                    m.putAll(kv);//java21有的特性
                    return m;
                });
//        打印结果
        map.forEach((k , v) -> {
            System.out.println(k + " = " + v);
        });
    }


}
